
local pairs, print
    = pairs, print

module (...)

local currentState, nextState, lastState = {}, {}, {}

local nextStruck, currentStruck = {}, {}
local nextStruckCount, currentStruckCount = 0, 0

function declareKeyDown(k)
  nextState[k] = true
  nextStruckCount = nextStruckCount + 1
  nextStruck[nextStruckCount] = k
end

local function eachstruck_aux(_, i)
  i = i + 1
  if (i > currentStruckCount) then
    return nil
  else
    return i, currentStruck[i]
  end
end

function eachstruck()
  return eachstruck_aux, nil, 0
end

function declareKeyUp(k)
  nextState[k] = nil
end

function isKeyDown(k)
  return not not currentState[k]
end

function wasKeyStruck(k)
  return currentState[k] and not lastState[k]
end

function wasKeyReleased(k)
  return lastState[k] and not currentState[k]
end

function refresh()
  currentState, nextState, lastState = nextState, lastState, currentState
  -- nextState should be a copy of currentState
  for k in pairs(nextState) do
    nextState[k] = nil
  end
  for k,v in pairs(currentState) do
    nextState[k] = v
  end
  nextStruckCount, currentStruckCount = 0, nextStruckCount
  currentStruck, nextStruck = nextStruck, currentStruck
end
 